package com.quick.calcu.controller;

import com.quick.calcu.entity.Student;
import com.quick.calcu.entity.Teacher;
import com.quick.calcu.entity.User;
import com.quick.calcu.service.RegisterService;
import com.quick.calcu.service.StudentService;
import com.quick.calcu.service.TeacherService;
import com.quick.calcu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RegisterService registerService;

    // 注册用户
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody User user) {

        Map<String, Object> result = new HashMap<>();
        try {
            // 先保存用户基础信息
            boolean success = registerService.registerWithRole(user);

            if (success) {
                result.put("code", "200");
                result.put("data", user);
                result.put("message", "注册成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("code", "400");
                result.put("data", user);
                result.put("message", "该用户已注册，请登录！");
                return ResponseEntity.ok(result);
            }
        } catch (IllegalArgumentException e) {
            result.put("code", "200");
            result.put("data", user);
            result.put("message", "注册失败2");
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常堆栈，方便调试
            result.put("code", "200");
            result.put("data", user);
            result.put("message", "注册失败3");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }


        // 用户登录
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> loginParams) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 从JSON参数中获取用户名和密码
            String username = loginParams.get("username");
            String password = loginParams.get("password");

            // 校验参数是否存在
            if (username == null || password == null) {
                throw new IllegalArgumentException("用户名和密码不能为空");
            }

            User user = userService.login(username, password);

            if (user == null) {
                result.put("code", "300");
                result.put("message", "登录失败：用户不存在！");
                result.put("data", user);
            } else if (user.getPassword() == null) {
                result.put("code", "400");
                result.put("message", "登录失败：密码错误！");
                result.put("data", user);
            } else {
                result.put("code", "200");
                result.put("message", "登录成功");
                result.put("data", user);
            }
            return ResponseEntity.ok(result);
        } catch (IllegalArgumentException e) {
            result.put("code", "200");
            result.put("success", false);
            result.put("message", "登录失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "登录失败：服务器内部错误");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    // 根据类型查询用户列表
    @PostMapping("/list") // 修改为POST请求以支持JSON
    public ResponseEntity<Map<String, Object>> listByType(@RequestBody Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userType = params.get("userType") != null ?
                    Integer.valueOf(params.get("userType")) : null;
            List<User> users = userService.listByType(userType);
            result.put("code", "200");
            result.put("message", "查询成功");
            result.put("data", users);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    // 修改密码
    @PutMapping("/updatePassword")
    public ResponseEntity<Map<String, Object>> updatePassword(@RequestBody Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();
        try {
            Long userId = params.get("userId") != null ?
                    Long.valueOf(params.get("userId")) : null;
            String oldPassword = params.get("oldPassword");
            String newPassword = params.get("newPassword");

            // 校验必要参数
            if (userId == null || oldPassword == null || newPassword == null) {
                throw new IllegalArgumentException("用户ID、旧密码和新密码不能为空");
            }

            boolean success = userService.updatePassword(userId, oldPassword, newPassword);
            result.put("code", "200");
            result.put("data", success);
            result.put("message", success ? "密码修改成功" : "密码修改失败");
            return success ? ResponseEntity.ok(result) : ResponseEntity.badRequest().body(result);
        } catch (IllegalArgumentException e) {
            result.put("success", false);
            result.put("message", "修改失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "修改失败：服务器内部错误");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
}